const config = require('../config/index.js')
const redis = require('redis')

let num = 0
let dbInstance = null

/**
 * 获取数据库实例
 * @returns
 */

async function getInstance () {
 if (!dbInstance) {
  dbInstance = await redis.createClient({
   port:"6379", host:'localhost',
   // auth_pass: 'yourpassword', // 如果 Redis 服务器设置了密码，请在这里提供
  });
 }
 return dbInstance
}

/**
 * 数据库操作
 * @param {*} dbName 数据库名称
 * @param {*} collectionName 集合名称
 * @returns
 */

async function Redis (dbName) {
 const Rd = await getInstance()
 if(num==0) await Rd.connect()
 if(num>10000) num = 1
 num++
 console.log('redis 连接 connecting:')
 // 处理连接错误
 Rd.on('error', (err) => {
  console.error('Redis client error:', err);
 })
 async function set (key,value) {
  /*数据库查询*/
  return await Rd.set(key,value)
 }
 async function get (key) {
  return new Promise((resolve, reject) => {
   resolve(Rd.get(key));
  });
 }
 async function update (key,value) {
  return await Rd.set(key,value)
 }

 async function del (key) {
  return await Rd.set(key)
 }

 async function disconect () {
  num = 0
  await Rd.disconect()
 }


 // return Rd
 return {
  Rd, num, set, get,
  del, update,disconect
 }
}

module.exports = { Redis: Redis }
